package org.example.meetingsystem.interceptor;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.meetingsystem.annotation.RequireAuth;
import org.example.meetingsystem.entity.User;
import org.example.meetingsystem.enums.UserRole;
import org.example.meetingsystem.enums.UserStatus;
import org.example.meetingsystem.mapper.UserMapper;
import org.example.meetingsystem.util.JwtUtil;
import org.example.meetingsystem.util.ResponseUtil;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;

@Component
@RequiredArgsConstructor
@Slf4j
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;
    private final UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;


        RequireAuth requireAuth = handlerMethod.getMethodAnnotation(RequireAuth.class);
        if (requireAuth == null) {
            requireAuth = handlerMethod.getBeanType().getAnnotation(RequireAuth.class);
        }

        if (requireAuth == null) {
            return true;
        }

        // 获取token
        String token = jwtUtil.getTokenFromRequest(request);
        if (token == null) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(ResponseUtil.unauthorized("未登录或token已过期")));
            return false;
        }

        try {
            // 验证token
            String username = jwtUtil.getUsernameFromToken(token);
            User user = userMapper.selectByUsername(username);

            if (user == null || jwtUtil.isTokenExpired(token)) {
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(ResponseUtil.unauthorized("用户不存在或token已过期")));
                return false;
            }

            // 检查用户状态
            if (user.getStatus() != UserStatus.ACTIVE) {
                response.setStatus(HttpStatus.FORBIDDEN.value());
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(ResponseUtil.forbidden("账号已被冻结")));
                return false;
            }

            // 检查角色权限
            UserRole[] allowedRoles = requireAuth.roles();
            if (allowedRoles.length > 0) {
                UserRole userRole = jwtUtil.getRoleFromToken(token);
                boolean hasPermission = Arrays.asList(allowedRoles).contains(userRole);
                if (!hasPermission) {
                    response.setStatus(HttpStatus.FORBIDDEN.value());
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write(JSON.toJSONString(ResponseUtil.forbidden("权限不足")));
                    return false;
                }
            }

            // 将用户信息存储到请求中
            request.setAttribute("currentUser", user);

        } catch (Exception e) {
            log.error("JWT验证失败", e);
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(ResponseUtil.unauthorized("token无效")));
            return false;
        }

        return true;
    }
}